package com.zzld.modules.maintenance.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.github.abel533.entity.Example;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.zzld.core.sms.SenderSms;
import com.zzld.core.utils.Base64Coder;
import com.zzld.core.utils.CookieUtils;
import com.zzld.core.utils.DateUtil;
import com.zzld.core.utils.OrderUtil;
import com.zzld.core.utils.UuidUtil;
import com.zzld.modules.autoinn.entity.Collar;
import com.zzld.modules.autoinn.entity.Coupon;
import com.zzld.modules.autoinn.entity.Customer;
import com.zzld.modules.autoinn.entity.Expense;
import com.zzld.modules.autoinn.entity.ProductPing;
import com.zzld.modules.autoinn.entity.Store;
import com.zzld.modules.autoinn.service.IAreaService;
import com.zzld.modules.autoinn.service.ICollarService;
import com.zzld.modules.autoinn.service.IConponService;
import com.zzld.modules.autoinn.service.ICustomerService;
import com.zzld.modules.autoinn.service.IExpenseService;
import com.zzld.modules.autoinn.service.IProductPingService;
import com.zzld.modules.autoinn.service.IProductService;
import com.zzld.modules.autoinn.service.IStoreService;
import com.zzld.modules.maintenance.entity.Matnexpense;
import com.zzld.modules.maintenance.entity.Matnexpensepath;
import com.zzld.modules.maintenance.entity.Matnproduct;
import com.zzld.modules.maintenance.service.IMatnexpenseService;
import com.zzld.modules.maintenance.service.IMatnexpensepathService;
import com.zzld.modules.maintenance.service.IMatnproductService;
import com.zzld.modules.maintenance.service.IPathService;
import com.zzld.modules.wechat.WeChat;
import com.zzld.modules.wechat.bean.WeChatBuyPost;
import com.zzld.modules.wechat.oauth.Oauth;
import com.zzld.modules.wechat.oauth.Pay;
import com.zzld.modules.wechat.util.ConfKit;
import com.zzld.modules.wechat.util.Tools;
import com.zzld.modules.wxsys.entity.WXAccount;
import com.zzld.modules.wxsys.service.IWXAccountService;

@Controller
@RequestMapping("/weixin/f/matenance/by/userpay")
public class WXMtanPayController {

	private String payInfo = "wx/matenance/pay_info";

	@Autowired
	private ICustomerService customerService;

	@Autowired
	private IAreaService areaService;

	@Autowired
	private IPathService pathService;

	@Autowired
	private IMatnproductService mtnproductService;

	@Autowired
	private IProductService productService;

	@Autowired
	private IMatnexpenseService expenseService;
	
	@Autowired
	private IMatnexpensepathService expensepathService;
	
	@Autowired
	private IWXAccountService wxAccountService;

	@Autowired
	private IStoreService storeService;

	@Autowired
	private IProductPingService productPingService;

	@Autowired
	private IConponService couponService;

	@Autowired
	private ICollarService collarService;


	private static final String STATUC_SUCCESS = "SUCCESS";
	private static final String STATUC_FAIL = "FAIL";
	private final String notify_url = "http://auto.nxsh114.com/zzld/weixin/f/matenance/by/userpay/notice";

	@RequestMapping(method = RequestMethod.GET)
	public String pay(Model model, HttpServletRequest request) {
		String openid = CookieUtils.getCookie(request, "autoinn_session");
		String wxaccount = CookieUtils.getCookie(request, "wx_session");
		Customer customer = null;
		try {
			
			  openid = Base64Coder.decode(openid);
			  wxaccount =Base64Coder.decode(wxaccount);
			 
			//openid = "123";
			//wxaccount = "12312321";
			customer = customerService.findCustomer(wxaccount, openid);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String city = CookieUtils.getCookie(request, "str");
		String cheng = CookieUtils.getCookie(request, "stor");
		String proids = CookieUtils.getCookie(request, "proids");
		
		if (city != null) {
			if (city.indexOf("区") == -1) {
				model.addAttribute("city", areaService.selectbyid(city)
						.getAreaname());
			} else {
				model.addAttribute("city", city);
			}
		}
		try {
			String html = "";
			if (proids != null) {

				String[] prids = proids.split(",");

				for (int i = 0; i < prids.length; i++) {
					html += "<li><input type=\"hidden\" value=\""
							+ mtnproductService.selectByPrimaryKey(prids[i])
									.getXprice()
							+ "\"/>"
							+ mtnproductService.selectByPrimaryKey(prids[i])
									.getProductname()
							+ "<span class=\"price\">"
							+ mtnproductService.selectByPrimaryKey(prids[i])
									.getXprice() + "元</span></li>";

				}

				model.addAttribute(
						"lei",
						pathService.selectByPrimaryKey(
								CookieUtils.getCookie(request, "pathlei"))
								.getPathname());

			} else {
				html = "<li>暂无数据</li>";
			}
			String storeid = request.getParameter("storeid");
			model.addAttribute("men", storeService.selectByPrimaryKey(storeid)
					.getName());
			model.addAttribute("storeid", storeid);
			String pathid = request.getParameter("pathid");
			model.addAttribute("propathid", pathid);
			Example e = new Example(Matnproduct.class);
			e.createCriteria().andEqualTo("storeId", storeid)
					.andEqualTo("pathId", pathid);
			Matnproduct product = mtnproductService.selectByExample(e).get(0);
			html += "<li><input type=\"hidden\" value=\"" + product.getXprice()
					+ "\"/>" + product.getProductname() + "<span class=\"price\">"
					+ product.getXprice() + "元</span></li>";
			model.addAttribute("ht", html);

		} catch (Exception e) {
			e.printStackTrace();
		}
		//优惠券
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("nowtime", new Date());
		map.put("wcaccount", wxaccount);
		map.put("openid", openid);
		List<Coupon> list1 = couponService.selectbyzhifu(map);
		
		model.addAttribute("coupon", list1.size()==0?null:list1);
		model.addAttribute("customer", customer);
		model.addAttribute("stor", cheng);
		return payInfo;
	}

	public double pricea(String balance, String xprice) {
		double yue = Double.valueOf(balance == null ? "0" : balance);
		double che = Double.valueOf(xprice.replace(",", ""));
		double res = (yue * 1000000) - (che * 1000000); // 余额
		return res / 1000000;

	}

	@RequestMapping(method = RequestMethod.POST)
	public String userpay(Model model, ModelMap modelmap,
			HttpServletRequest request) {
		
		  String openid = CookieUtils.getCookie(request, "autoinn_session");
		  String wxaccount = CookieUtils.getCookie(request, "wx_session");
		
		//String wxaccount = "12312321";
		//sString openid = "123";
		Customer customer = null;
		try {

		   openid = Base64Coder.decode(openid);
		   wxaccount =Base64Coder.decode(wxaccount);
			customer = customerService.findCustomer(wxaccount, openid);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 订单信息
		String username = request.getParameter("name");
		String phone = request.getParameter("phone");
		String storeid = request.getParameter("storeid");
		String propathid = request.getParameter("propathid");
		String cheng = CookieUtils.getCookie(request, "stor");
		String addres = cheng + request.getParameter("chg");

		String pathid = CookieUtils.getCookie(request, "pathlei");
		String proids = CookieUtils.getCookie(request, "proids");

		String zhitype = request.getParameter("zhitype");
		String cop = request.getParameter("cop");

		BigDecimal yue = customer.getSurplus();//用户余额
      
		String des="";
		
		 String[] copmtemp =null;
		//优惠券
		if(cop!=null && !cop.equals("0,0,0")){
		   copmtemp = cop.split(",");//1:金额,2:优惠券类型,3:领票id
		}
		
		try {
			Double sumzong=0.00;
			Double co=0.00;
			if(cop!=null && !cop.equals("0,0,0")){
				co = Double.valueOf(copmtemp[0]);
				des+="使用优惠券:"+co+"元，";
			}
			//计算一共花销费用
			String[] prois = proids.split(",");
			for(int u = 0;u<prois.length;u++){
				sumzong=sumzong+mtnproductService.selectByPrimaryKey(prois[u]).getXprice().doubleValue();
			}
			// 服务商保养服务费
			Example e1 = new Example(Matnproduct.class);
			e1.createCriteria().andEqualTo("storeId", storeid)
					.andEqualTo("pathId", propathid);

			Matnproduct product = mtnproductService.selectByExample(e1)
					.get(0);
			sumzong=(sumzong+product.getXprice().doubleValue())-co;
			System.out.println("保养总共花费"+sumzong+"元");
			
			//选择支付方式
			if(Integer.valueOf(zhitype).equals(1)){
				//微信支付
				if(sumzong==0 || sumzong<0){
					des+="实际支付："+sumzong+"元";
					//跳出微信支付记录消费清单
					//开始添加消费记录
					Matnexpensepath me1 = new Matnexpensepath();
					me1.setId(UuidUtil.uuid().toString());
					me1.setPathid(CookieUtils.getCookie(request, "pathlei"));
					me1.setCreatetime(new Date());
					me1.setCustomerid(customer.getCustomerId());
					me1.setDes(des);
					me1.setWcaccount(wxaccount);
					me1.setState(1);
					me1.setStoreid(storeid);
					if(expensepathService.saveSelective(me1)>0){
						//判断是否使用优惠券使用则修改优惠券状态
						if(cop!=null && !cop.equals("0,0,0")){
							// 改变优惠券是否使用
							collarService.updatebystate(1,copmtemp[2].toString());
						}
						for(int i = 0;i<prois.length;i++){
							Matnexpense me2 = new Matnexpense();
							me2.setId(UuidUtil.uuid().toString());
							me2.setPrice(mtnproductService.selectByPrimaryKey(prois[i]).getYprice());
							me2.setYfprice(mtnproductService.selectByPrimaryKey(prois[i]).getXprice());
							me2.setInnertime(new Date());
							me2.setIspr(0);
							me2.setProductid(prois[i]);
							me2.setExpensepathid(me1.getId());
							me2.setIspro(0);
							expenseService.saveSelective(me2);
						}
						Matnexpense me3 = new Matnexpense();
						me3.setId(UuidUtil.uuid().toString());
						me3.setPrice(product.getYprice());
						me3.setYfprice(product.getXprice());
						me3.setInnertime(new Date());
						me3.setIspr(0);
						me3.setProductid(product.getProductid());
						me3.setExpensepathid(me1.getId());
						me3.setIspro(0);
						if(expenseService.saveSelective(me3)>0){
						modelmap.put("errormsg", "支付成功");
						try {
							//客户短信
							SenderSms.send(customer.getPhoneNum(),
									"尊敬的会员:您已支付保养费用"
											+ customer.getNickname().toString()
											+ "支付保养费用明细："+des+"【E爱车】");
							//服务商短信
							Store d = storeService.selectByPrimaryKey(me1.getStoreid());
							SenderSms.send(d.getTel(),
									"尊敬的服务商:会员("+customer.getNickname().toString()
									        +",联系电话:"+customer.getPhoneNum()+","
											+ "已支付保养费用,请注意查看【E爱车】");
							//后台短信通知
							SenderSms.send("15652434490",
									"尊敬的服务商:会员("+customer.getNickname().toString()
									        +",联系电话:"+customer.getPhoneNum()+","
											+ "已支付保养费用,请注意发货【E爱车】");
						} catch (Exception e) {
							// TODO 自动生成的 catch 块
							modelmap.put("errormsg", "出现异常");
						}
					  }
					}
					return null; //订单记录
			   }else{
				 //微信支付
					String orderNum = OrderUtil.generateOrderNum("XF");
					boolean isweixin = WeChat.isWeiXin(request);
					if(isweixin){
						// 获取订单号
						// 对商品名截取, 去除空格
						String productName = "E爱车保养服务";
						productName = productName.replaceAll(" ", "");
						productName = productName.length() > 17 ? productName
								.substring(0, 17) + "..." : productName;
						// package 参数封装----------------------------- //
						Map<String, String> params = new HashMap<String, String>();
						params.put("appid", ConfKit.get("AppId"));
						params.put("mch_id", ConfKit.get("partnerId"));
						params.put("nonce_str", RandomStringUtils.random(32,
								"abcdefghijklmnopqrstuvwxyz0123456789"));
						params.put("body", productName); // 商品描述。
						params.put("out_trade_no", orderNum); // 商户系统内部的订单号
						params.put(
								"total_fee",
								String.valueOf(
										Math.abs(BigDecimal.valueOf(sumzong)
												.multiply(new BigDecimal(100))
												.doubleValue())).replace(".0", "")); // 订单总金额
						modelmap.put("qian", params.get("total_fee").toString());
						String ip = getIp(request);// 获取ip
						params.put("spbill_create_ip", ip); // ip	
						params.put("notify_url", notify_url);
						modelmap.put("urkl", notify_url);
						
						params.put("trade_type", "JSAPI"); // 现金支付币种,取值： 1 （人民币）
						String collarid="";
						if(cop==null || cop.equals("0,0,0")){
							collarid="0";
						}else{
							collarid=copmtemp[2];
						}
						System.out.println("开始附加数据");
						System.out.println("回调url："+notify_url);
						
						String zhides="";
						
						System.out.println("开始记录订单");
						
						Matnexpensepath me1 = new Matnexpensepath();
						me1.setId(UuidUtil.uuid().toString());
						me1.setPathid(CookieUtils.getCookie(request, "pathlei"));
						me1.setCreatetime(new Date());
						me1.setCustomerid(customer.getCustomerId());
						
						zhides += "微信支付："+sumzong;
						if(cop!=null && !cop.equals("0,0,0")){
							//使用优惠券
						 System.out.println("修改优惠券");
						 Collar a = collarService.selectByPrimaryKey(copmtemp[2].toString());
						 Coupon c = couponService.selectByPrimaryKey(a.getCounponId());
						 zhides+=",使用"+c.getCouponName();
						}
						System.out.println(zhides);
						me1.setDes(zhides);
						System.out.println("开始记录订单1");
						me1.setWcaccount(wxaccount);
						me1.setState(2);
						System.out.println("开始记录订单3");
						me1.setStoreid(storeid);
						System.out.println("开始记录订单2");
						if(expensepathService.saveSelective(me1)>0){
							System.out.println("开始记录订单4");
							//判断是否使用优惠券使用则修改优惠券状态
							if(cop!=null && !cop.equals("0,0,0")){
								// 改变优惠券是否使用
								collarService.updatebystate(1,copmtemp[2].toString());
							}
							System.out.println("开始记录订单55");
							String pathido = CookieUtils.getCookie(request, "pathlei");
							System.out.println("开始记录订单666");
						
							String[] proidso =CookieUtils.getCookie(request, "proids").split(",");
							String oq=CookieUtils.getCookie(request, "proids");
							System.out.println("记录qq:"+oq);
							System.out.println("开始记录订单777");
							for(int i = 0;i<proidso.length;i++){
								Matnexpense me2 = new Matnexpense();
								me2.setId(UuidUtil.uuid().toString());
								me2.setPrice(mtnproductService.selectByPrimaryKey(proidso[i]).getYprice());
								me2.setYfprice(mtnproductService.selectByPrimaryKey(proidso[i]).getXprice());
								me2.setInnertime(new Date());
								me2.setIspr(0);
								me2.setProductid(proidso[i]);
								me2.setExpensepathid(me1.getId());
								me2.setIspro(0);
								expenseService.saveSelective(me2);
							}
							System.out.println("第五步");
							Example e4 = new Example(Matnproduct.class);
							e4.createCriteria().andEqualTo("storeId", storeid)
									.andEqualTo("pathId", pathido);

							
							Matnexpense me3 = new Matnexpense();
							me3.setId(UuidUtil.uuid().toString());
							me3.setPrice(product.getYprice());
							me3.setYfprice(product.getXprice());
							me3.setInnertime(new Date());
							me3.setIspr(0);
							me3.setProductid(product.getProductid());
							me3.setExpensepathid(me1.getId());
							me3.setIspro(0);
							if(expenseService.saveSelective(me3)>0){
								System.out.println("第6步");
							try {
								//客户短信
								SenderSms.send(customer.getPhoneNum(),
										"尊敬的会员:您已支付保养费用"
												+ customer.getNickname().toString()
												+ "支付保养费用明细："+des+"【E爱车】");
								//服务商短信
								Store d = storeService.selectByPrimaryKey(me1.getStoreid());
								SenderSms.send(d.getTel(),
										"尊敬的服务商:会员("+customer.getNickname().toString()
										        +",联系电话:"+customer.getPhoneNum()+","
												+ "已支付保养费用,请注意查看【E爱车】");
								//后台短信通知
								SenderSms.send("15652434490",
										"尊敬的服务商:会员("+customer.getNickname().toString()
										        +",联系电话:"+customer.getPhoneNum()+","
												+ "已支付保养费用,请注意发货【E爱车】");
							} catch (Exception e) {
								// TODO 自动生成的 catch 块
								
							}
						  }
						}
					
						
						params.put("attach",collarid+","+storeid+","+propathid+","+me1.getId());	
						params.put("openid", openid);
						
						// 获取parepay_id
						try {
							String prepayid = Pay.getPrepayid(params);
							System.out.println("预支付" + prepayid);
							params.put("prepay_id", prepayid);
							if (prepayid != null && prepayid.length() > 10) {

								// 参数
								String timeStamp = Long.toString(new Date()
										.getTime() / 1000); // 时间戳，自1970年以来的秒数
								String nonceStr = RandomStringUtils.random(32,
										"abcdefghijklmnopqrstuvwxyz0123456789"); // 32位随机数
								String packagestring = "prepay_id=" + prepayid;
								SortedMap<String, String> nativeObj = new TreeMap<String, String>();
								nativeObj.put("appId", ConfKit.get("AppId"));
								nativeObj.put("timeStamp", timeStamp);
								nativeObj.put("nonceStr", nonceStr);
								nativeObj.put("package", packagestring);
								nativeObj.put("signType", "MD5");
								String paySign = Pay.createSign(nativeObj,
										ConfKit.get("partnerKey"));// 构造签名
								nativeObj.put("paySign", paySign);

								modelmap.put("appid", ConfKit.get("AppId"));
								modelmap.put("timeStamp", timeStamp);
								modelmap.put("nonceStr", nonceStr);
								modelmap.put("package", packagestring);
								modelmap.put("paySign", paySign);
								modelmap.put("isweixin", 1);
								
							

							}

						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ExecutionException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}else{
						modelmap.put("errormsg", "该版本不支持微信支付，请升级至微信5.0");
					}
			   }
			}else if(Integer.valueOf(zhitype).equals(2)){
				//余额支付
				Double y = yue.doubleValue();// 当前用户余额
			    if(y-sumzong<0){
						modelmap.put("errormsg", "支付失败");
						return null;
			    }

			    des+="余额支付："+sumzong+"元";
				//跳出微信支付记录消费清单
				//开始添加消费记录
				Matnexpensepath me1 = new Matnexpensepath();
				me1.setId(UuidUtil.uuid().toString());
				me1.setPathid(CookieUtils.getCookie(request, "pathlei"));
				me1.setCreatetime(new Date());
				me1.setCustomerid(customer.getCustomerId());
				me1.setDes(des);
				me1.setWcaccount(wxaccount);
				me1.setState(1);
				me1.setStoreid(storeid);
				if(expensepathService.saveSelective(me1)>0){
					//判断是否使用优惠券使用则修改优惠券状态
					if(cop!=null && !cop.equals("0,0,0")){
						// 改变优惠券是否使用
						collarService.updatebystate(1,copmtemp[2].toString());
					}
					for(int i = 0;i<prois.length;i++){
						Matnexpense me2 = new Matnexpense();
						me2.setId(UuidUtil.uuid().toString());
						me2.setPrice(mtnproductService.selectByPrimaryKey(prois[i]).getYprice());
						me2.setYfprice(mtnproductService.selectByPrimaryKey(prois[i]).getXprice());
						me2.setInnertime(new Date());
						me2.setIspr(0);
						me2.setProductid(prois[i]);
						me2.setExpensepathid(me1.getId());
						me2.setIspro(0);
						expenseService.saveSelective(me2);
					}
					Matnexpense me3 = new Matnexpense();
					me3.setId(UuidUtil.uuid().toString());
					me3.setPrice(product.getYprice());
					me3.setYfprice(product.getXprice());
					me3.setInnertime(new Date());
					me3.setIspr(0);
					me3.setProductid(product.getProductid());
					me3.setExpensepathid(me1.getId());
					me3.setIspro(0);
					if(expenseService.saveSelective(me3)>0){
					modelmap.put("errormsg", "支付成功");
					//修改用户余额
					Customer d = new Customer();
					d.setCustomerId(customer.getCustomerId());
					if(sumzong<=customer.getSurplus().doubleValue()){
					BigDecimal uy = new BigDecimal(customer.getSurplus().doubleValue()-sumzong);
					d.setSurplus(uy);
					}				
					customerService.updateByPrimaryKeySelective(d);
					try {
						//客户短信
						SenderSms.send(customer.getPhoneNum(),
								"尊敬的会员:您已支付保养费用"
										+ customer.getNickname().toString()
										+ "支付保养费用明细："+des+"【E爱车】");
						//服务商短信
						Store ds = storeService.selectByPrimaryKey(me1.getStoreid());
						SenderSms.send(ds.getTel(),
								"尊敬的服务商:会员("+customer.getNickname().toString()
								        +",联系电话:"+customer.getPhoneNum()+","
										+ "已支付保养费用,请注意查看【E爱车】");
						//后台短信通知
						SenderSms.send("15652434490",
								"尊敬的服务商:会员("+customer.getNickname().toString()
								        +",联系电话:"+customer.getPhoneNum()+","
										+ "已支付保养费用,请注意发货【E爱车】");
					} catch (Exception e) {
						// TODO 自动生成的 catch 块
						modelmap.put("errormsg", "出现异常");
					}
				  }
				}
				return null; //订单记录
			}else if(Integer.valueOf(zhitype).equals(3)){
				//现金支付
				   des+="现金支付："+sumzong+"元";
					//跳出微信支付记录消费清单
					//开始添加消费记录
					Matnexpensepath me1 = new Matnexpensepath();
					me1.setId(UuidUtil.uuid().toString());
					me1.setPathid(CookieUtils.getCookie(request, "pathlei"));
					me1.setCreatetime(new Date());
					me1.setCustomerid(customer.getCustomerId());
					me1.setDes(des);
					me1.setWcaccount(wxaccount);
					me1.setState(0);
					me1.setStoreid(storeid);
					if(expensepathService.saveSelective(me1)>0){
						//判断是否使用优惠券使用则修改优惠券状态
						if(cop!=null && !cop.equals("0,0,0")){
							// 改变优惠券是否使用
							collarService.updatebystate(1,copmtemp[2].toString());
						}
						for(int i = 0;i<prois.length;i++){
							Matnexpense me2 = new Matnexpense();
							me2.setId(UuidUtil.uuid().toString());
							me2.setPrice(mtnproductService.selectByPrimaryKey(prois[i]).getYprice());
							me2.setYfprice(mtnproductService.selectByPrimaryKey(prois[i]).getXprice());
							me2.setInnertime(new Date());
							me2.setIspr(0);
							me2.setProductid(prois[i]);
							me2.setExpensepathid(me1.getId());
							me2.setIspro(0);
							expenseService.saveSelective(me2);
						}
						Matnexpense me3 = new Matnexpense();
						me3.setId(UuidUtil.uuid().toString());
						me3.setPrice(product.getYprice());
						me3.setYfprice(product.getXprice());
						me3.setInnertime(new Date());
						me3.setIspr(0);
						me3.setProductid(product.getProductid());
						me3.setExpensepathid(me1.getId());
						me3.setIspro(0);
						if(expenseService.saveSelective(me3)>0){
						modelmap.put("errormsg", "支付成功");
						//修改用户余额
						Customer d = new Customer();
						d.setCustomerId(customer.getCustomerId());
						if(sumzong<=customer.getSurplus().doubleValue()){
						BigDecimal uy = new BigDecimal(customer.getSurplus().doubleValue()-sumzong);
						d.setSurplus(uy);
						}				
						customerService.updateByPrimaryKeySelective(d);
						try {
							//客户短信
							SenderSms.send(customer.getPhoneNum(),
									"尊敬的会员:您已支付保养费用"
											+ customer.getNickname().toString()
											+ "支付保养费用明细："+des+"【E爱车】");
							//服务商短信
							Store ds = storeService.selectByPrimaryKey(me1.getStoreid());
							SenderSms.send(ds.getTel(),
									"尊敬的服务商:会员("+customer.getNickname().toString()
									        +",联系电话:"+customer.getPhoneNum()+","
											+ "已支付保养费用,请注意查看【E爱车】");
							//后台短信通知
							SenderSms.send("15652434490",
									"尊敬的服务商:会员("+customer.getNickname().toString()
									        +",联系电话:"+customer.getPhoneNum()+","
											+ "已支付保养费用,请注意发货【E爱车】");
						} catch (Exception e) {
							// TODO 自动生成的 catch 块
							modelmap.put("errormsg", "出现异常");
						}
					  }
					}
					return null; //订单记录
			}
		} catch (Exception e) {
			modelmap.put("errormsg", "出现异常");
		}
		return "/wx/autoinn/wxPay";
	}

	/**
	 * 支付通知
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "notice")
	public void notice(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		WeChatBuyPost postData = null;
		String postname = "";
		try {
			InputStream in = request.getInputStream();
			// 转换微信post过来的xml内容

			XStream xs = new XStream(new DomDriver());
			xs.alias("xml", WeChatBuyPost.class);
			String xmlMsg = Tools.inputStream2String(in);
			postData = (WeChatBuyPost) xs.fromXML(xmlMsg);
			if (postData.getReturn_code().equals("SUCCESS")
					&& postData.getResult_code().equals("SUCCESS")) {
				// 此处调用订单查询接口验证是否交易成功

				// 支付成功，商户处理后同步返回给微信参数

				// ------------------------------

				// 处理业务开始,添加充值记录,给用户余额添加金额

				// ------------------------------
                
				String[] strtemp = postData.getAttach().split(",");
				System.out.println("1.记录:"+strtemp.length);
				try {
                  System.out.println("支付成功");
					Oauth oauthInfo = new Oauth();
					WXAccount wxaccount = wxAccountService.findwxaccount(
							postData.getAppid(), oauthInfo.getSecret());
					if (wxaccount != null) {
						// 充值记录不存在则添加


						// 操作用户余额
                       
						Customer entity = customerService
								.findCustomer(wxaccount.getAcccountId(),
										postData.getOpenid());

						
						if (entity != null) {
						
							BigDecimal surplus = entity.getSurplus();
							// 分转元

							System.out.println("开始记录3");
							BigDecimal total_fee = BigDecimal.valueOf(
									(long) postData.getTotal_fee()).divide(
									new BigDecimal(100));
						
							Matnexpensepath p = new Matnexpensepath();
							p.setId(strtemp[3]);
							p.setState(1);
							expensepathService.updateByPrimaryKeySelective(p);
							
						}
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block

					e.printStackTrace();
				}

				// ------------------------------

				// 处理业务完毕

				// ------------------------------

				
			
				String noticeStr = setXML(STATUC_SUCCESS, "");
				response.getWriter().write(noticeStr);
			} else {
				// 支付失败

				String noticeStr = setXML(STATUC_FAIL, "支付失败");
				response.getWriter().write(noticeStr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 支付失败

		String noticeStr = setXML(STATUC_FAIL, "支付失败");
		response.getWriter().write(noticeStr);
	}

	public static String setXML(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code
				+ "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}

	/**
	 * 获取ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		if (request == null)
			return "";
		String ip = request.getHeader("X-Requested-For");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String[] rip = ip.split(",");
		if (StringUtils.isNotBlank(ip) && StringUtils.isNotBlank(rip[0])) {
			ip = rip[0];
		} else {
			ip = "127.0.0.1";
		}

		return ip;
	}

	// 金额验证
	public static boolean isNumber(String str) {
		java.util.regex.Pattern pattern = java.util.regex.Pattern
				.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
		java.util.regex.Matcher match = pattern.matcher(str);
		if (match.matches() == false) {
			return false;
		} else {
			return true;
		}
	}

}
